//
//  ERCoverView.m
//  TestWebViewPagable
//
//  Created by zhuxuhong on 2016/12/19.
//  Copyright © 2016年 zhuxh. All rights reserved.
//

#import "ERCoverView.h"

@interface ERCoverView()

@property(nonatomic)CGFloat lastX; //上次滑动位置


@end

@implementation ERCoverView
{
    // 包含的子view
    NSArray<UIView *> *_contentViews;
}

static BOOL initial = true;
static CGFloat beginX;
static CGFloat lastX;
static BOOL directionToLeft = false;
static NSInteger current = 0;
static NSInteger total = 5;
static BOOL viewAdded = false;
static UIView *tempView = nil;
static CGRect frame;
static BOOL animating = false;
static BOOL noOperating; //不允许操作

-(instancetype)initWithFrame: (CGRect)frame
                contentViews: (NSArray<UIView *> * _Nonnull )contentViews{
    
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.masksToBounds = true;
        
        _contentViews = contentViews;
        total = _contentViews.count;
        
        // 添加滑动手势
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(actionOfPan:)];
        [self addGestureRecognizer:pan];
        
        // 转屏通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
    }
    return self;
}

-(void)deviceOrientationDidChange: (NSNotification*)noti{
    [self resetSubviews];
}


// 重设frame
-(void)resetSubviews{
    for (UIView *v in _contentViews) {
        v.frame = self.bounds;
        
        // 阴影
        v.layer.shadowColor = [UIColor blackColor].CGColor; // 阴影颜色
        v.layer.shadowOffset = CGSizeMake(0, 0); // 偏移距离
        v.layer.shadowOpacity = 0.5; // 不透明度
        v.layer.shadowRadius = 10.0; // 半径
    }
}

-(void)setCurrentPageIndex:(NSInteger)current{
    if (_contentViews.count == 0) {
        return;
    }
    if (current < 0) {
        current = 0;
    }
    else if (current > _contentViews.count-1) {
        current = _contentViews.count-1;
    }
    _currentPageIndex = current;
    [self addSubview: _contentViews[_currentPageIndex]];
    tempView = _contentViews[_currentPageIndex];
}

-(void)actionOfPan: (UIPanGestureRecognizer*)pan
{
    CGFloat x = [pan locationInView:pan.view].x;

    switch (pan.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            [self panBeganWithLocationPointX:x];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self panChangedWithLocationPointX:x];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            [self panEndedWithLocationPointX:x];
        }
            break;
        default:
        {
            [self panEndedWithLocationPointX:x];
        }
            break;
    }
}


#pragma mark - 手势方法

#pragma mark Began
-(void)panBeganWithLocationPointX: (CGFloat)x{
    NSLog(@"began - current: %ld",current);
    //            NSLog(@"began x: %f translation x: %f",location,translation);
    viewAdded = false;
    noOperating = false;
    beginX = 0;
    lastX = x;
}

#pragma mark Changed
-(void)panChangedWithLocationPointX: (CGFloat)x{
    if (animating) {
        return;
    }
    
    //1. 方向判断
    CGFloat delta = x - lastX;
    if (delta == 0) {
        return;
    }
    if (delta < 0) {
        //                NSLog(@"<----");
        directionToLeft = true;
    }
    else{
        //                NSLog(@"---->");
        directionToLeft = false;
    }
    lastX = x;
    
    //2. 条件判断
    if (initial && current == 0 && !directionToLeft) {
        //                NSLog(@"第一页 --->");
        noOperating = true;
        viewAdded = true;
        return;
    }
    if(initial && current == total-1 && directionToLeft){
        //                NSLog(@"最后一页 <---");
        noOperating = true;
        viewAdded = true;
        return;
    }
    
    //3. 添加view
    if (!viewAdded && !directionToLeft) { //向右
        tempView = _contentViews[current-1];
        [self addSubview:tempView];
        viewAdded = true;
        beginX = 0;
        frame = tempView.frame;
    }
    else if(!viewAdded && directionToLeft){ //向左
        tempView = [self.subviews lastObject];
        [self insertSubview:_contentViews[current+1] belowSubview:tempView];
        frame = tempView.frame;
        beginX = CGRectGetMaxX(frame) - x;
        viewAdded = true;
    }
    
    //4. 改变frame
    frame.origin.x = x + beginX - CGRectGetWidth(frame);
    if (frame.origin.x > 0) {
        frame.origin.x = 0;
    }
    tempView.frame = frame;
    initial = false;
}

#pragma mark Ended
-(void)panEndedWithLocationPointX: (CGFloat)x{
    if (animating || noOperating) {
        return;
    }
    
    //1. 进行动画
    animating = true;
    frame.origin.x = -CGRectGetWidth(frame);
    if (!directionToLeft) {
        frame.origin.x = 0;
    }
    
    // 动画时间别太长
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        tempView.frame = frame;
    } completion:^(BOOL finished)
    {
        if (finished)
        {
            //2. view的移除
            if (directionToLeft) { // <---
                [tempView removeFromSuperview];
                UIView *v = [self.subviews lastObject];
                if (!v) {
                    return;
                }
                tempView = v;
            }
            else if(!directionToLeft){ // --->
                UIView *v = [self.subviews firstObject];
                if (!v) {
                    return;
                }
                [v removeFromSuperview];
            }
            
            //3. current改变
            NSInteger cur = [_contentViews indexOfObject:tempView];
            if (cur < 0 || cur > total-1){
                return;
            }
            if (cur != current) {
                current += directionToLeft ? 1 : -1;
                current = current < 0 ? 0 : current;
                current = current > total-1 ? total-1 : current;
            }
            NSLog(@"finished - current: %ld",current);
            
            //4. 参数重设
            animating = false;
            lastX = 0;
            initial = current == 0 || current == total-1;
        }
        else{
            animating = true;
        }
    }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
